<?
/**
 * $Id: IndexController.php 1254 2008-09-09 08:39:51Z lule $
 * Modul strony glownej
 *
 */
class IndexController extends MainController implements ControllerInterface {


	private static $listType = '__list_type__';

		public $tableConfig = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'rank'	=> 'product.rank',
				'_' => 'rank',
			),
			'v' => 'a',
			't' => 10
		)
	);

	protected $tables = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'_' => 'popularity',
			),
			'v' => 'a',
			't' => 10
		)
	); 

	/**
	 * Strona glowna
	 *
	 */

	public function IndexAction($param) {
		$this->AddDescription("");
		$this->AddTitle(Utils::Translate('Passion Shared',Registry::Get('_user')));

		$productsIds = SessionProxy::GetValue('__products__ids__', null);
		if(!empty($productsIds))
		{
			SessionProxy::ClearValue('__products__ids__');
		}
		
		
		
		$propIds = array();
			$propSql = '';
			SessionProxy::ClearValue('__product_list_selected_properties__');
			$selectedProperties = array();
			if(Request::IsPost())
			{
				$selectedProperties = Request::Get('prop');

			}


			$idLang =  Registry::Get('APPLICATION_LANGUAGE_ID').'';

			if(isset($_GET['switch']))
			{
				$viewClass = SessionProxy::GetValue(self::$listType, 'list');
				if($viewClass == 'list')
				{
					SessionProxy::SetValue(self::$listType, 'box');
				} else {
					SessionProxy::SetValue(self::$listType, 'list');
				}
			}
			$viewClass = SessionProxy::GetValue(self::$listType, 'list');

			

			// category
			$categoryObjs = CategoryDAL::GetResult(
				CategoryDAL::GetDalDataObj(
					array(
						'condition' => array(
							'category.id_category' => array('4')
						),
						'join' => array(
							'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')'
						)
					)
				)
			);


			$_categoryKey = $categoryObjs[0]->getParentCategoryObj()->getSlug();
			$param['categoryKey'] = $_categoryKey;
			$_subCategoryKey = $categoryObjs[0]->getSlug();
			$param['subCategoryKey'] = $_subCategoryKey;
			
			$this->smarty->assign('categoryKey', $_categoryKey);
			$this->smarty->assign('subCategoryKey', $_subCategoryKey);
			$this->smarty->assign('param_from_url', array('categoryKey'=>$categoryObjs[0]->getParentCategoryObj()->getSlug(), 'subCategoryKey'=>$categoryObjs[0]->getSlug()));
			$this->smarty->assign('listType', $viewClass);
			//$this->smarty->assign('categoryKey', $categoryObjs[0]->getParentCategoryObj()->getSlug());
			//$this->smarty->assign('subCategoryKey',$categoryObjs[0]->getSlug());
//var_dump($this->smarty->get_template_vars());
			if(count($categoryObjs) != 2)
			{
				//return $this->AddRedirect(Router::GenerateUrl('default', array()), 0);
			}

			$categoryObj = null;
			$parentCategoryObj = null;

			foreach($categoryObjs as $_cat)
			{
				if($_cat->getSlug() == $categoryObjs[0]->getParentCategoryObj()->getSlug())
				{
					$parentCategoryObj = $_cat;
				} else {
					$categoryObj = $_cat;
				}
			}
			$parentCategoryObj = $categoryObjs[0]->getParentCategoryObj();


			$this->smarty->assign('parentCategoryObj', $parentCategoryObj);
			$this->smarty->assign('categoryObj', $categoryObj);

			$categoryDescription = $categoryObj->getCategoryDescription();

			$this->AddDescription($categoryDescription->getSeoDescription());
			$this->AddKeywords($categoryDescription->getSeoKeywords());

			//$this->AddTitle($parentCategoryObj->getName());
			//$this->AddTitle($categoryObj->getName());

			//$this->AddBreadCrumb($categoryObj->getName());

			/* koniec - ustawianie wstepnych */

			// filtry opcji
			$dalData = PropertyDAL::GetDalDataObj(
				array(
					'condition' => array(
						'' => array(
							array(
								'condition'=>'',
								'value'=> '( id_category = ' . $parentCategoryObj->getId() . ' OR id_category = ' . $categoryObj->getId() .')')
						),
						'active' => array(1),
						'show_in_filters' => array(1),
					),
					'join' => array(
						'PropertyDescription' => ' LEFT JOIN property_description ON (property_description.id_property = property.id_property AND property_description.id_language = ' . $idLang . ' ) ',
						'PropertyGroup' => ' LEFT JOIN property_group ON (property.id_property_group = property_group.id_property_group)'
					)
				)
			);



			$filterProperties = PropertyDAL::GetResult($dalData);
			
			
			// comapnies
			$dalData =	ManufacturerDAL::GetDalDataObj(
				array(
					'condition' => array(
							'manufacturer.active' => array(1),
							'product.active' => array(1)
						),
					'join' => array(
						'Product' => ' LEFT JOIN product ON (product.id_manufacturer = manufacturer.id_manufacturer)'
						)
					)	
				);
			
			if($categoryObj)
			{
				$dalData->addCondition('product.id_category', $categoryObj->getId());
			} else {
				$dalData->addCondition('manufacturer.id_manufacturer', $activeCompanyObj->getId());
			}		
			
//			if(!empty($selectedCompanies))
//			{
//				$dalData->addCondition('manufacturer.id_manufacturer', '(' . implode(', ', $selectedCompanies) . ')', 'IN');
//			}			
			
			$categoriesIds = array($parentCategoryObj->getId());
			if($categoryObj) $categoriesIds = array_merge ($categoriesIds, array($categoryObj->getId()));

			
//			$dalData->addSelectFields('ProductsCount', '(SELECT count(id_product) FROM product a WHERE 1 = 1 AND a.active = 1 AND a.id_manufacturer = manufacturer.id_manufacturer '. $propSql .')');
			$countResults = PropertyValueDAL::GetDefaultsWithCountsForCompanies(null, $categoriesIds, (empty($activeCompanyObj)?null:$activeCompanyObj->getId()));

			$dalData->setGroupBy('manufacturer.id_manufacturer');
			$dalData->setOrderBy('manufacturer.name');
			$result = ManufacturerDAL::GetResult($dalData);			
			
			foreach($result as $k => $v)
			{
				if(isset($countResults[$v->getId()]))
				{
					$result[$k]->setProductsCount($countResults[$v->getId()]);
				}
			}				
			


			
			$this->smarty->assign('filterCompanies', $result);	
			$this->smarty->assign('selectedCompanies', array());


			$_ids = array();

			foreach($filterProperties as $k => $v)
			{
				$_ids[] = $v->getId();
			}



			if(!empty($_ids))
			{
				$dalData = PropertyValueDAL::GetDalDataObj(
						array(
							'condition' => array(
								'' => array(array(
									'condition' => '',
									'value' => '(id_property = ' . implode(' OR id_property = ', $_ids) .')'
									)
								),
								'type' => array(
									'condition' => '=', 
									'value' => Registry::Get('METRIC_SYSTEM_TYPE')									
								)
							)
						)
					);
				$dalData->addCondition('parent', 'NULL', 'IS');
				$dalData->addCondition('id_product', 'NULL', 'IS');
				$dalData->setGroupBy('value');
				$dalData->setOrderBy('property_value.id_property_value');
				
				$pv = PropertyValueDAL::GetResult($dalData);

				$_pv = array(); // wartosci
				$_pdv = array(); // defaultowe wartosci
				if(!empty($pv))
				{
					
					$vArr = array();

					
					$categoriesIds = array($parentCategoryObj->getId());
					if($categoryObj) $categoriesIds = array_merge ($categoriesIds, array($categoryObj->getId()));
					
					$results = PropertyValueDAL::GetDefaultsWithCounts(null, $categoriesIds, (empty($activeCompanyObj)?null:$activeCompanyObj->getId()));
					
					foreach($pv as $_p)
					{
						if($_p->getValue() == '')
						{
							continue;
						}

						if($_p->getIdProduct())
						{
							if(!isset($_pv[$_p->getIdProperty()]))
							{
								$_pv[$_p->getIdProperty()] = array();
							}
							$_pv[$_p->getIdProperty()][] = $_p;
							if($_p->getParent())
							{
								if(!isset($vArr[$_p->getParent()])) $vArr[$_p->getParent()] = 0;
								$vArr[$_p->getParent()] = $vArr[$_p->getParent()] + $_p->getProductsCount();
							}
						} 
						else
						{
							if(!isset($_pdv[$_p->getIdProperty()]))
							{
								$_pdv[$_p->getIdProperty()] = array();
							}
							if(isset($results[$_p->getId()]))
							{
								$_p->setproductsCount($results[$_p->getId()]);
							} else {
								$_p->setproductsCount(0);
							}
							
							$_pdv[$_p->getIdProperty()][] = $_p;						
						}
					}
					
						
					
				}

				foreach($filterProperties as $k => $v)
				{
					if(isset($_pdv[$v->getId()]))
					{
						$v->setPropertyValue($_pdv[$v->getId()]);
						$filterProperties[$k] = $v;
					} elseif (isset($_pv[$v->getId()]))
					{
						$v->setPropertyValue($_pv[$v->getId()]);
						$filterProperties[$k] = $v;
					}
				}

			}


			$this->smarty->assign('filterProperties', $filterProperties);


			/* produkty */
			$dalData = ProductDAL::GetDalDataObj(array(
				'tableData' => $this->tableParams['products_list'],
				'condition' => array(
					'id_category' => array($categoryObj->getId()),
					'product.active' => array(1),
					'manufacturer.active' => array(1),
				),
				'join' => array(
					'ProductDescription' => ' LEFT JOIN product_description ON (product.id_product = product_description.id_product AND product_description.id_language = '.Registry::Get('APPLICATION_LANGUAGE_ID').')',
					'Manufacturer' => ' LEFT JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)'
				)
			));
			
			$dalData->addJoin('PropertyValue', ' LEFT JOIN property_value ON(property_value.id_product = product.id_product)');
			$dalData->setGroupBy('product.id_product');
			$dalData->addCondition('property_value.parent', 'NULL', 'IS NOT');			


			$this->smarty->assign('selectedProperties', $selectedProperties);
			$this->smarty->assign('selectedPropertyValues', array());

			$dalData2 = clone $dalData;
			$dalData2->setAsCount('count(distinct(product.id_product))');
			$dalData2->setLimit("");
			
			$this->smarty->assign('c', 	ProductDAL::GetResult($dalData2));

			// products
			$dalData->setCount(False);

			$productsList = ProductDAL::GetResult($dalData);

			foreach($productsList as $product) {
				$dalObjr = ProductRankingDAL::GetDalDataObj();
				$dalObjr->addCondition('product_ranking.id_product', $product->getId());
				$dalObjr->addJoin('ProductRankingType', ' LEFT JOIN product_ranking_type ON (product_ranking.type=product_ranking_type.id_product_ranking_type AND product_ranking_type.active = 1) ');
				$productRanking = ProductRankingDAL::GetResult($dalObjr);
				$product->setProductRanking($productRanking);

				$dalObj = ProductVotesRankingDAL::GetDalDataObj();
				$dalObj->addJoin('ProductVotesType', ' JOIN product_votes_type on ( product_votes_type.id_product_votes_type = product_votes_ranking.id_product_votes_type ) ');
				$dalObj->addCondition('id_product', $product->getId());

				$productVotes = ProductVotesRankingDAL::GetResult($dalObj);
				$product->setProductVotes($productVotes);
				$this->smarty->assign('productVotes', $productVotes);
			}

			$this->smarty->assign('productsList', $productsList);

			$this->RunShared('CategoriesAndBrands', $param);

			$this->AddScript('category.js');

			
			//galerie
			
			$dalData = UserGalleryDAL::GetDalDataObj();
			$dalData->addCondition('user_gallery.active', '1');
			$dalData->setOrderBy('date DESC');
			$dalData->setLimit('4');
			$dalData->addJoin('User', 'Join user ON user_gallery.id_user=user.id_user');
			$result = UserGalleryDAL::GetResult($dalData);
			$this->smarty->assign('userGallery', $result);
			
		
		//$this->RunShared('CategoriesAndBrands', $param);
	}

	public function QuizAction($param) {

	}

	/**
	 * Czesc wspolna wszystkich podstron
	 *
	 */
	public function PreDispatch($param) {
		$this->Run($param);
		if($this->partialTemplate == 'Index.tpl' && $this->userLoggedIn) {
			$this->RunShared('Wall',array('userLoggedIn' => $this->userLoggedIn, 'id_user' => $this->user->getId()));
		}
	}

	public function PostDispatch($param) {
		
		// nagłówek strony
		$this->RunShared('Header', $param);

		
		// footer
		$this->RunShared('Footer', $param);
	}

}

